//
//  LeftViewController.m
//  小豌旅行
//
//  Created by wyzcWLB on 16/9/27.
//  Copyright © 2016年 wyzcWLB. All rights reserved.
//

#import "LeftViewController.h"
#import <AFNetworking.h>
#import <UIImageView+WebCache.h>
#import "leftModel.h"
#import "rightModel.h"
#import "leftCell.h"
#import "rightCell.h"
#import "HeadCollectionReusableView.h"
#import <MJRefresh.h>

#define Screen_Width [UIScreen mainScreen].bounds.size.width
#define Screen_Height [UIScreen mainScreen].bounds.size.height

@interface LeftViewController ()<UITableViewDataSource,UITableViewDelegate,UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout>
@property (strong, nonatomic) UITableView *leftTableView;
@property (strong, nonatomic) UICollectionView *rightcollectionView;
@property(nonatomic,strong)NSMutableArray *leftArray;
@property(nonatomic,strong)NSMutableArray *rightArray;
@property(nonatomic,strong)UICollectionView *rightcollectionHeaderView;
@end

@implementation LeftViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    
    //设置导航栏标题
    self.title = @"看锦囊";
 
    [self createcollectionView];
    [self createTableView];
    [self addLeftBack];
    
    [self requestData];
    self.rightcollectionView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(requestData)];
    
    [self requestLeftData];
    [self requestRightData];

}
#pragma mark 懒加载
//重写getter方法，用到的时候才初始化，经典的引用就是视图控制器的view

-(NSMutableArray *)leftArray
{
    if (_leftArray == nil) {
        _leftArray= [[NSMutableArray alloc]init];
    }
    return _leftArray;
}
-(NSMutableArray *)rightArray
{
    if (_rightArray == nil) {
        _rightArray= [[NSMutableArray alloc]init];
    }
    return _rightArray;
}
#pragma mark 加载左边数据
-(void)requestLeftData
{
    

    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    [manager GET:@"http://open.qyer.com/qyer/guide/category_list?client_id=qyer_ios&client_secret=cd254439208ab658ddf9&count=20&lat=40.03616355444207&lon=116.3638803295888&page=1&track_app_channel=App%2520Store&track_app_version=6.8&track_device_info=iPhone7%2C1&track_deviceid=7B6FA080-F9FB-44C1-B932-401CD69CD5D2&track_os=ios%25209.1&v=1" parameters:nil success:^(NSURLSessionDataTask *task, id responseObject) {
        NSDictionary *rootDic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
        
        NSArray *array = [rootDic objectForKey:@"data"];
        for (NSDictionary *dic in array) {
            leftModel *model = [[leftModel alloc]init];
            [model setValuesForKeysWithDictionary:dic];
            [self.leftArray addObject:model];
        }
        // NSLog(@"%@",self.leftArray);
        [self.leftTableView reloadData];
        [self.leftTableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] animated:NO scrollPosition:UITableViewScrollPositionTop];
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        
    }];
    
}
#pragma mark 加载锦囊最新数据
-(void)requestData
{
    [self.rightArray removeAllObjects];
    [self.rightcollectionView.mj_header beginRefreshing];
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager GET:@"http://open.qyer.com/qyer/guide/channel_list?client_id=qyer_ios&client_secret=cd254439208ab658ddf9&count=20&id=999999&lat=40.03616355444207&lon=116.3638803295888&page=1&track_app_channel=App%2520Store&track_app_version=6.8&track_device_info=iPhone7%2C1&track_deviceid=7B6FA080-F9FB-44C1-B932-401CD69CD5D2&track_os=ios%25209.1&v=1" parameters:nil success:^(NSURLSessionDataTask *task, id responseObject) {
        NSDictionary *rootDic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
        [_rightArray removeAllObjects];
        rightModel *model = [[rightModel alloc]mj_setKeyValues:rootDic];
        self.rightArray = model.data;
        [self.rightcollectionView reloadData];
        [self.rightcollectionView.mj_header endRefreshing];
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        
        
    }];
    
}
#pragma mark 加载右边数据
-(void)requestRightData
{
    leftModel *model = _leftArray[_leftTableView.indexPathForSelectedRow.row];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    NSString *str1 = @"http://open.qyer.com/qyer/guide/channel_list?client_id=qyer_ios&client_secret=cd254439208ab658ddf9&count=20&id=%ld&lat=40.03616355444207&lon=116.3638803295888&page=1&track_app_channel=App%@";
    NSString *str2 = @"%2520Store&track_app_version=6.8&track_device_info=iPhone7%2C1&track_deviceid=7B6FA080-F9FB-44C1-B932-401CD69CD5D2&track_os=ios%25209.1&v=1";
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    NSString *url = [NSString stringWithFormat:str1,model.id,str2];
    [manager GET:url parameters:nil success:^(NSURLSessionDataTask *task, id responseObject) {
        
        NSDictionary *rootDic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
        [_rightArray removeAllObjects];
        rightModel *model = [[rightModel alloc]mj_setKeyValues:rootDic];
        self.rightArray = model.data;
        [self.rightcollectionView reloadData];
        
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        
    }];
    
}

-(void)createcollectionView
{
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
    layout.scrollDirection = UICollectionViewScrollDirectionVertical;
    _rightcollectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(80, 0, Screen_Width-80, Screen_Height) collectionViewLayout:layout];
    self.rightcollectionView.contentInset = UIEdgeInsetsMake(64, 0, 0, 0);
    _rightcollectionView.dataSource = self;
    _rightcollectionView.delegate = self;
    _rightcollectionView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
    [self.view addSubview:_rightcollectionView];
    _rightcollectionView.backgroundColor = [UIColor whiteColor];
    
    [_rightcollectionView  registerNib:[UINib nibWithNibName:@"rightCell" bundle:nil] forCellWithReuseIdentifier:@"rightCell"];
  
    [_rightcollectionView registerNib:[UINib nibWithNibName:@"HeadCollectionReusableView" bundle:nil] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader  withReuseIdentifier:@"HeadCollectionReusableView"];
    
}

-(void)createTableView
{
    _leftTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 64, 80, Screen_Height) style:UITableViewStylePlain];
    _leftTableView.dataSource= self;
    _leftTableView.delegate = self;
    _leftTableView.rowHeight = 70;
    //    _leftTableView.bounces = NO;
    _leftTableView.showsHorizontalScrollIndicator = NO;
    _leftTableView.showsVerticalScrollIndicator = NO;
    [self.leftTableView registerNib:[UINib nibWithNibName:NSStringFromClass([leftCell class]) bundle:nil] forCellReuseIdentifier:@"leftCell"];
    
    
    // 设置inset
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.leftTableView.contentInset = UIEdgeInsetsMake(0, 0, 64, 0);
    
    [self.view addSubview:self.leftTableView];
    
}
#pragma mark 设置返回按钮
-(void)addLeftBack{
    
    UIButton *back = [UIButton buttonWithType:UIButtonTypeCustom];
    [back setTitle:@"返回" forState:UIControlStateNormal];
    [back setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [back setTitleColor:[UIColor redColor] forState:UIControlStateHighlighted];
    
    [back setImage:[UIImage imageNamed:@"navigationButtonReturn"] forState:UIControlStateNormal];
    [back setImage:[UIImage imageNamed:@"navigationButtonReturnClick"] forState:UIControlStateHighlighted];
    
    //移动按钮位置
    back.contentEdgeInsets = UIEdgeInsetsMake(0, -15, 0, 0);
    
    //手势无法执行原因：手势被清空 或者手势执行其他方法了(就是手势的协议监听方法去了)
    //代理设置成空就是没有执行对象
    self.navigationController.interactivePopGestureRecognizer.delegate=nil;
    
    //自动适应大小
    [back sizeToFit];
    
    UIBarButtonItem *item = [[UIBarButtonItem alloc]initWithCustomView:back];
    self.navigationItem.leftBarButtonItem = item;
    
    [back addTarget:self action:@selector(goToBack) forControlEvents:UIControlEventTouchUpInside];
}
-(void)goToBack{
    
    [self.navigationController popViewControllerAnimated:YES];
    
}




-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.leftArray.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    leftCell *cell = [tableView dequeueReusableCellWithIdentifier:@"leftCell"];
    leftModel *model = self.leftArray[indexPath.row];
    cell.textLabel.text = model.cnname;
    return cell;
    
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    //    leftModel *model = self.leftArray[indexPath.row];
    //    self.ID = model.id;
    
    [self requestRightData];
}





-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return _rightArray.count;
}
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    DaModel *model = _rightArray[section];
    return model.guides.count;
}
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    rightCell *right = [collectionView dequeueReusableCellWithReuseIdentifier:@"rightCell" forIndexPath:indexPath];
    DaModel *dataModel = self.rightArray[indexPath.section];
    GuidesModel *model = dataModel.guides[indexPath.row];
    NSString* imageStr=[NSString stringWithFormat:@"%@/260_390.jpg?cover_updatetime=%@",model.cover,model.cover_updatetime];
    [right.imageV sd_setImageWithURL:[NSURL URLWithString:imageStr]];
    right.imageV.layer.cornerRadius = 5;
    right.imageV.layer.masksToBounds = YES;
    return right;
    
}
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return CGSizeMake((Screen_Width-90)/3, 160);
}
-(CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section
{
    return 1;
}
//设置最小列间距
-(CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section
{
    return 1;
}

#pragma mark 设置头视图
-(UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    UICollectionReusableView *reusableview = nil;
    
    if (kind == UICollectionElementKindSectionHeader)
    {
    HeadCollectionReusableView *head = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"HeadCollectionReusableView" forIndexPath:indexPath];
        
    DaModel *model = _rightArray[indexPath.section];
    head.headTitle.text = [NSString stringWithFormat:@"  %@",model.name];
    return head;
    }
    return reusableview;
}
#pragma mark 设置组头视图尺寸
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section
{
    return CGSizeMake(Screen_Width-80, 30);
}

@end
